package com.codez.unionpay.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author zhengdechao
 * @createTime : 2019-05-20
 *
 */

//@Sharable
public class LocalServerHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(" 貌似有新连接了......");
		super.channelActive(ctx);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(" 客户端貌似断开了 ");
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf in = (ByteBuf) msg;
		System.out.println(in.toString(CharsetUtil.UTF_8));

		ChannelFuture future = ctx.channel().writeAndFlush(
				Unpooled.copiedBuffer("服务端已经收到您的消息[" + in.toString(CharsetUtil.UTF_8) + "]", CharsetUtil.UTF_8));
//		if (in.toString(CharsetUtil.UTF_8).equals("e")) {
//			future.addListener(ChannelFutureListener.CLOSE);
//		}
//		future.addListener(ChannelFutureListener.CLOSE);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

}
